package com.uniknow.app.operate.impl;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.uniknow.app.AppConfig;
import com.uniknow.app.AppContext;
import com.uniknow.app.bin.ResponseBean;
import com.uniknow.app.bin.UserBean;
import com.uniknow.app.http.AsyncHttpResponseHandler;
import com.uniknow.app.http.RequestParams;
import com.uniknow.app.manager.UserManager;
import com.uniknow.app.operate.BaseListener;
import com.uniknow.app.operate.HttpPath;
import com.uniknow.app.operate.LoginOperate;
import com.uniknow.app.util.SynchttpClient;
import com.uniknow.app.util.Sysout;

public class LoginOperateImpl implements LoginOperate{
	private Context mContext;
	
	public LoginOperateImpl(Context context){
		this.mContext = context;
	}
	
	private SynchttpClient getClient(){
		return SynchttpClient.getClient();
	}

	@Override
	public void login(UserBean user,final BaseListener listener) {
		
		RequestParams params = new RequestParams();
		params.put("user.name", user.getUserName());
		params.put("user.passwd", user.getPassWord());
		getClient().post(HttpPath.LOGIN, params, new AsyncHttpResponseHandler(listener){
			
			@Override
			public void onSuccess(String content) {	
				Sysout.i(LoginOperateImpl.class,content);
				try{
					GsonBuilder builder = new GsonBuilder();
					builder.excludeFieldsWithoutExposeAnnotation();
					Gson gson = builder.create();
					ResponseBean rs = (ResponseBean) gson.fromJson(content, ResponseBean.class);
					if (rs.OK()) {
						listener.onSuccess(content);
						UserBean user = (UserBean) gson.fromJson(gson.toJson(rs.getContent()),UserBean.class);
						UserManager userManager = UserManager.getManager(mContext);
						AppContext.user = user;
						AppConfig.UserName = AppContext.user.getUserName();
						AppConfig.U_ID = AppContext.user.getUserid()+"";
						AppConfig.PassWord = AppContext.user.getPassWord();
						userManager.add(user);
					}else{
						listener.onError(rs.errorInfo());
					}
				}catch(JsonSyntaxException e){
					Sysout.i(LoginOperateImpl.class,e.getMessage());
					listener.onError(e.getMessage());
				}
				
			}
			
		});
		
	}

}
